package top.rish.converter.springboot;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.rish.converter.core.factory.SolonDictConvertFactory;
import top.rish.converter.core.annotation.handler.DictConvertHandler;

import java.util.Map;
import java.util.Objects;

@ControllerAdvice
public class DictConverterResponseBodyInterceptor
        implements
        ApplicationContextAware,
        ResponseBodyAdvice<Object> {

    private ApplicationContext context;

    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }
 
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        Map<String, DictConvertHandler> beansOfType = this.context.getBeansOfType(DictConvertHandler.class);
        beansOfType.values().forEach(SolonDictConvertFactory::registerHandler);
        SolonDictConvertFactory.registerDictEntityFields(body);
        Object converted = SolonDictConvertFactory.convert(body);
        if(!Objects.equals(body,converted)){
            body = converted;
        }
        return body;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }


}